package com.flyco.modules.task.util;

import com.flyco.modules.system.mapper.SysLogMapper;
import okhttp3.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author hui_li
 * @Date 2024/1/25 13:33
 * @Version 1.0
 */
public class SapWebServiceRequestUtil {

    public static Map<String, String> requestSap(String wsdlUrl, String action, String bodyXml) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(600, TimeUnit.SECONDS)
                .writeTimeout(600, TimeUnit.SECONDS)
                .readTimeout(600, TimeUnit.SECONDS)
                .build();
        MediaType mediaType = MediaType.parse("application/soap+xml");
        RequestBody body = RequestBody.create(mediaType, bodyXml);
        Request request = new Request.Builder()
                .url(wsdlUrl)
                .method("POST", body)
                .addHeader("action", action)
                .addHeader("charset", "UTF-8")
                .addHeader("Content-Type", "application/soap+xml")
                .addHeader("Authorization", "Basic V1NfVVNFUjoxMjM0NTY=")
                .addHeader("Accept", "application/soap+xml")
                .addHeader("Connection", "close")
                .addHeader("Accept-Language", "ZH")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String respStr = response.body().string();
            //手动关闭链接
            response.close();
            return getSapResult(respStr);
        } catch (IOException e) {
            //清空连接池
            client.connectionPool().evictAll();
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    private static Map<String, String> getSapResult(String respStr) {
        Map<String, String> map = new HashMap<>(3);
        map.put("originalResult", respStr);
        if (true) {
            respStr = respStr.toLowerCase();
            int beginIndex = respStr.indexOf("<type>");
            if (beginIndex > 0) {
                int endIndex = respStr.indexOf("</type>");
                String type = respStr.substring(beginIndex + 6, endIndex);
                map.put("type", type);
            } else {
                map.put("type", "E");
                map.put("message", "没有找到SapResult的type信息");
                return map;
            }
        }

        if (true) {
            int beginIndex = respStr.indexOf("<message>");
            if (beginIndex > 0) {
                int endIndex = respStr.indexOf("</message>");
                String message = respStr.substring(beginIndex + 9, endIndex);
                map.put("message", message);
            } else {
                map.put("type", "E");
                map.put("message", "没有找到SapResult的message信息");
                return map;
            }
        }
        return map;
    }

}
